import {
  FC,
  ReactElement,
  memo,
  useState,
  useCallback,
  useEffect,
} from "react";
import { Layout, Menu } from "antd";
import { sideRoutes, SideRoutesProps } from "../../constant/routers";
import { Link } from "react-router-dom";

const { SubMenu, Item: MenuItem } = Menu;
const { Sider } = Layout;

interface IProps {}

const renderSideLink = ({
  title,
  key,
  icon,
  path = "",
  children,
}: SideRoutesProps) =>
  !children ? (
    <MenuItem key={key} icon={icon} title={title}>
      <Link to={path}>{title}</Link>
    </MenuItem>
  ) : (
    <SubMenu key={key} icon={icon} title={title}>
      {children.map(renderSideLink)}
    </SubMenu>
  );

const Side: FC<IProps> = (): ReactElement => {
  const [selectedKeys, setSelectedKeys] = useState(
    window.location.hash.replace("#/admin/", "")?.split("/") ?? [
      sideRoutes[0]["key"],
    ]
  );

  const hashChange = useCallback(() => {
    const keys = window.location.hash.replace("#/admin/", "")?.split("/");
    // console.log("keys:", keys);
    keys && setSelectedKeys(keys);
  }, []);

  useEffect(() => {
    window.addEventListener("hashchange", hashChange);
    return () => {
      window.removeEventListener("hashchange", hashChange);
    };
  }, [hashChange]);

  return (
    <Sider>
      <Menu
        mode='inline'
        selectedKeys={selectedKeys}
        openKeys={selectedKeys.length > 1 ? [selectedKeys[0]] : undefined}
        style={{ height: "100%" }}
      >
        {sideRoutes.map(renderSideLink)}
      </Menu>
    </Sider>
  );
};

export default memo(Side);
